package com.yangchoi.lib_base.network

import com.yangchoi.lib_base.network.interceptor.DynamicBaseUrlInterceptor
import com.yangchoi.lib_base.network.interceptor.HeaderInterceptor
import com.yangchoi.lib_base.network.interceptor.LoggingInterceptor
import com.yangchoi.lib_base.network.interceptor.ReadCookieInterceptor
import com.yangchoi.lib_base.network.interceptor.WriteCookieInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

// 动态修改baseUrl的拦截器,这个需要放在最外层,当做一个全局变量来使用,在需要的时候通过这个全局变量去修改并设置
// 不能重新New,重新New的话会是一个新的拦截器,无法修改并通知到retrofit
val dynamicBaseUrlInterceptor = DynamicBaseUrlInterceptor()

object RetrofitClient {

    /**
     * 请求超时时间
     */
    private const val DEFAULT_TIMEOUT = 30000
    private lateinit var SERVICE: ApiService

    //手动创建一个OkHttpClient并设置超时时间
    val retrofit: ApiService
        get() {
            if (!RetrofitClient::SERVICE.isInitialized) {
                SERVICE = Retrofit.Builder()
                    .client(okHttp)
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(ApiService.Base_Url)
                    .build()
                    .create(ApiService::class.java)
            }
            return SERVICE
        }

    //手动创建一个OkHttpClient并设置超时时间
    val okHttp: OkHttpClient
        get() {
            return OkHttpClient.Builder().run {
                addInterceptor(dynamicBaseUrlInterceptor)
                connectTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
                readTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
                writeTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
                addInterceptor(HeaderInterceptor())
                addInterceptor(WriteCookieInterceptor())
                addInterceptor(ReadCookieInterceptor())
                addInterceptor(LoggingInterceptor())
                //不验证证书
//                sslSocketFactory(createSSLSocketFactory())
//                hostnameVerifier(TrustAllNameVerifier())
                build()
            }
        }

//    private fun createSSLSocketFactory(): SSLSocketFactory {
//        lateinit var ssfFactory: SSLSocketFactory
//        try {
//            val sslFactory = SSLContext.getInstance("TLS")
//            sslFactory.init(null,  arrayOf(TrustAllCerts()), SecureRandom());
//            ssfFactory = sslFactory.socketFactory
//        } catch (e: Exception) {
//            print("SSL错误：${e.message}")
//        }
//        return ssfFactory
//    }


}